<div class="content">
    <div class="form-row row-fluid" id="div_form_bon_livraison">
        {% include "GdsVenteBundle::BonLivraison/form_bon_livraison.html.twig" %}
    </div>
</div>
<script type="text/javascript">


    $(document).ready(function() {
        $('#gds_ventebundle_bonlivraisonclienttype_client').val({{client.id}})
        $('#departement').val({{user.departement.id}})
        $('#gds_ventebundle_bonlivraisonclienttype_date').datepicker();
        $('#departement').attr('disabled', true);
        $('#retour2').hide()
        mdp = ""
        var fullDate = new Date();
        var twoDigitMonth = fullDate.getMonth()
        twoDigitMonth++
        twoDigitMonth += "";
        if (twoDigitMonth.length == 1)
            twoDigitMonth = "0" + twoDigitMonth;
        var twoDigitDate = fullDate.getDate() + "";
        if (twoDigitDate.length == 1)
            twoDigitDate = "0" + twoDigitDate;
        var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
        $("#gds_ventebundle_bonlivraisonclienttype_date").val(currentDate)
        setInterval(time, 1000);
        $('#form_bon_livraison').validate();
        $('#submit_form_bon_livraison').click(function() {
            $('#submit_form_bon_livraison').hide()
            $('#submit_form_bon_livraison_print').hide()
            $('#gds_ventebundle_bonlivraisonclienttype_reference').focus()
            if ($('#form_bon_livraison').valid()) {
                $.ajax({
                    url: '{{path("gds_devis_livrer")}}',
                    type: "POST",
                    datatype: 'json',
                    data: $('#form_bon_livraison').serialize() + '&articles={"articles":' + JSON.stringify(articles) + '}&heure=' + $('#heure').val() + '&facturable=' + $('#facturable').is(':checked') + '&departement=' + $("#departement option:selected").text() + '&id=' +{{id}} + '&mdp=' + mdp,
                    success: function(data) {
                        if (data.success) {
                            $.msgBox({
                                title: "Bon Livraison",
                                content: "Enregistrement Effectué avec succés",
                                type: "info",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    location.reload();
                                }
                            });
                        } else if (data.limit_depass) {
                            $.msgBox({
                                title: "Dépassement du Solde Client !!",
                                content: "mdp: <input id='mdp' type='password' />",
                                type: "confirm",
                                buttons: [
                                    {type: "submit", value: "Valider"},
                                    {type: "cancel", value: "Annuler"}
                                ],
                                afterShow: function() {
                                    $('#mdp').focus()
                                },
                                success: function(result) {
                                    if (result == "Valider") {
                                        if ($('#mdp').val() != '') {
                                            mdp = $('#mdp').val()
                                            $('#submit_form_bon_livraison').click()
                                        }
                                    }
                                }
                            });
                        } else {
                            $.msgBox({
                                title: "Bon Livraison",
                                content: "Erreur D'enregistrement",
                                type: "error",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    $('#submit_form_bon_livraison').show("slow")
                                    $('#submit_form_bon_livraison_print').show("slow")
                                }
                            });
                        }
                    },
                    error: function(e) {
                        $.msgBox({
                            title: "Bon Livraison",
                            content: "Erreur D'enregistrement",
                            type: "error",
                            buttons: [{value: "OK"}],
                            success: function(result) {
                                $('#submit_form_bon_livraison').show("slow")
                                $('#submit_form_bon_livraison_print').show("slow")
                            }
                        });
                    }
                })
            }
        })
        $('#submit_form_bon_livraison_print').click(function() {
            $('#submit_form_bon_livraison').hide()
            $('#submit_form_bon_livraison_print').hide()
            $('#gds_ventebundle_bonlivraisonclienttype_reference').focus()
            if ($('#form_bon_livraison').valid()) {
                $.ajax({
                    url: '{{path("gds_devis_livrer")}}',
                    type: "POST",
                    datatype: 'json',
                    data: $('#form_bon_livraison').serialize() + '&articles={"articles":' + JSON.stringify(articles) + '}&heure=' + $('#heure').val() + '&facturable=' + $('#facturable').is(':checked') + '&departement=' + $("#departement option:selected").text() + '&id=' +{{id}} + '&mdp=' + mdp,
                    success: function(data) {
                        if (data.success) {
                            Imprimer(data.numero)
                        } else if (data.limit_depass) {
                            $.msgBox({
                                title: "Dépassement du Solde Client !!",
                                content: "mdp: <input id='mdp' type='password' />",
                                type: "confirm",
                                buttons: [
                                    {type: "submit", value: "Valider"},
                                    {type: "cancel", value: "Annuler"}
                                ],
                                afterShow: function() {
                                    $('#mdp').focus()
                                },
                                success: function(result) {
                                    if (result == "Valider") {
                                        if ($('#mdp').val() != '') {
                                            mdp = $('#mdp').val()
                                            $('#submit_form_bon_livraison_print').click()
                                        }
                                    }
                                }
                            });
                        } else {
                            $.msgBox({
                                title: "Bon Livraison",
                                content: "Erreur D'enregistrement",
                                type: "error",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                    $('#submit_form_bon_livraison').show("slow")
                                    $('#submit_form_bon_livraison_print').show("slow")
                                }
                            });
                        }
                    },
                    error: function(e) {
                        $.msgBox({
                            title: "Bon Livraison",
                            content: "Erreur D'enregistrement",
                            type: "error",
                            buttons: [{value: "OK"}],
                            success: function(result) {
                                $('#submit_form_bon_livraison').show("slow")
                                $('#submit_form_bon_livraison_print').show("slow")
                            }
                        });
                    }
                })
            }
        })
        Array.prototype.remove = function(v) {
            this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1);
        }
        index = 0;
        nb_article = 1;
        // var index_array = Array();
        articles = new Array();
        $container = $('#gds_ventebundle_lignebonlivraisonclienttype');
        index = 0;
        nb_article = 1;
        {% for l,ligne in lignes %}
        add_ligne()
        $('#td_reference_' +{{l}}).html('{{ligne.article.reference}}')
        $('#td_designation_' +{{l}}).html('{{ligne.article.designation}}')
        $('#gds_ventebundle_' +{{l}} + '_quantite').val('{{ligne.quantite|number_format(2)}}')
        $('#td_prix_unitaire_ht_' +{{l}}).html('{{ligne.prixUnitaireHt}}')
        if ({{ligne.prixUnitaireHt}} >{{ligne.article.prixVente}}) {
            $('#tr_' +{{l}}).addClass('green');
            $('#td_prix_unitaire_ht_' +{{l}}).dblclick(function() {
                if ($('#tr_' +{{l}}).hasClass('red') || $('#tr_' +{{l}}).hasClass('green'))
                    changerPrixVente({{l}},{{ligne.article.prixVente}})
            })
        } else if ({{ligne.prixUnitaireHt}} <{{ligne.article.prixVente}}) {
            $('#tr_' +{{l}}).addClass('red');
            $('#td_prix_unitaire_ht_' +{{l}}).dblclick(function() {
                if ($('#tr_' +{{l}}).hasClass('red') || $('#tr_' +{{l}}).hasClass('green'))
                    changerPrixVente({{l}},{{ligne.article.prixVente}})
            })
        }

        tva_twig = {{ligne.tauxTva}}
        tva_twig = tva_twig.toFixed(2)
        $('#td_tva_' +{{l}}).html(tva_twig + '%')
        $('#gds_ventebundle_' +{{l}} + '_taux_remise').val('{{ligne.tauxRemise}}')
        $('#gds_ventebundle_' +{{l}} + '_article').val('{{ligne.article.id}}')
        var x = new Object();
        x.reference = $('#td_reference_' + {{l}}).html()
        x.designation = $('#td_designation_' + {{l}}).html()
        x.taux_tva = '{{ligne.tauxTva}}'
        x.remise = '{{ligne.tauxRemise}}'
        x.remise_max = '{{ligne.article.remiseMax}}'
        x.prix_vente = '{{ligne.prixUnitaireHt}}'
        x.quantite = '{{ligne.quantite}}'
        x.prix_vente_min_ttc = x.prix_vente * (1 + (x.taux_tva / 100)) * (1 - (x.remise_max / 100))
        x.name = x.reference + ' : ' + x.designation
        x.id = '{{ligne.article.id}}'
        articles[{{l}}] = x
        completerChamp('{{l}}')
        {% endfor %}
        RefraichirTaxe()
        setTousQuantite()
    });
    function completerChamp(i) {
        var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
        var quantite = article.quantite;
        var prix_vente = article.prix_vente;
        var tva = article.taux_tva;
        var remise = article.remise;
        var puttc = prix_vente
        puttc *= (1 + tva / 100)
        puttc *= (1 - remise / 100)
        puttc = puttc.toFixed(3)
        $('#td_prix_u_ttc_' + i).html(puttc);
        var total = puttc * quantite
        $('#td_total_' + i).html(total.toFixed(3));
        $('#gds_ventebundle_' + i + '_taux_remise').spinner({
            min: 0,
            max: article.remise_max,
            step: 1,
            places: 2,
            showOn: 'both'
        });
    }
    function changerPrixVente(i, prix_vente) {
        $.msgBox({
            title: "Changement Prix Vente Ht",
            content: "Voulez-vous changer le Prix Vente à :  " + prix_vente.toFixed(3),
            type: "info",
            buttons: [{value: "OUI"}, {value: "NON"}, {value: "ANNULER"}],
            success: function(result) {
                if (result == "OUI") {
                    $('#tr_' + i).removeClass('red')
                    $('#tr_' + i).removeClass('green')
                    var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
                    $('#td_prix_unitaire_ht_' + i).html(prix_vente.toFixed(3))
                    var old_remise = article.remise
                    var old_prix_vente = article.prix_vente
                    var taux_tva = article.taux_tva
                    var old_ttc = old_prix_vente * (1 + taux_tva / 100) * (1 - old_remise / 100)
                    article.prix_vente = prix_vente
                    changerPrixTtc(i, old_ttc)
                }
            }
        });
    }
    function changerPrixTtc(i, old_ttc) {
        $.msgBox({
            title: "Changement Prix Vente Ttc",
            content: "Voulez-vous changer Remise sans modifier PUTTC ?",
            type: "confirm",
            buttons: [{value: "OUI"}, {value: "NON"}],
            success: function(result) {
                if (result == "OUI") {
                    var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
                    var prix_vente = article.prix_vente
                    var taux_tva = article.taux_tva
                    var r = old_ttc / (prix_vente * (1 + taux_tva / 100))
                    var remise = (1 - r) * 100
                    if (remise < 0) {
                        $.msgBox({
                            title: "Remise Inférieur à 0 !!",
                            content: "Remise changé à 0",
                            type: "info",
                            buttons: [{value: "OK"}],
                        });
                        remise = 0
                        article.remise = remise
                    }
                    if (remise > article.remise_max) {
                        $.msgBox({
                            title: "Remise Max Dépassé",
                            content: "Voulez-vous changer le remise max à : " + remise.toFixed(2) + " ?",
                            type: "confirm",
                            buttons: [{value: "OUI"}, {value: "NON"}],
                            success: function(result) {
                                if (result == "OUI") {
                                    article.remise_max = remise
                                    $('#gds_ventebundle_' + i + '_taux_remise').spinner({
                                        min: 0,
                                        max: article.remise_max,
                                        step: 1,
                                        places: 2,
                                        showOn: 'both'
                                    });
                                    $('#gds_ventebundle_' + i + '_taux_remise').val(remise.toFixed(2))
                                    RefraichirTaxe()
                                } else {
                                    remise = article.remise_max
                                }
                                $('#gds_ventebundle_' + i + '_taux_remise').keyup()
                            }
                        });
                        article.remise = remise
                    }
                    $('#gds_ventebundle_' + i + '_taux_remise').val(remise.toFixed(2))
                }
                completerChamp(i)
                RefraichirTaxe()
            }
        });
    }
    function changeRemiseClient() {
        articles_to_modify = new Array()
        index_modify = new Array()
        $('#gds_ventebundle_lignebonlivraisonclienttype tr').each(function() {
            var ii = $(this).attr('id');
            ii = ii.split('_');
            ii = ii[1]
            articles_to_modify[articles_to_modify.length] = $('#gds_ventebundle_' + ii + '_article').val()
            index_modify[index_modify.length] = ii

        })
        $.ajax({
            url: '{{path("gds_vente_get_remises_client")}}',
            type: "POST",
            data: {'articles': articles_to_modify, 'raison_social': $('#gds_ventebundle_bonlivraisonclienttype_client').val()},
            dataType: 'json',
            success: function(data) {
                var count_index_modify = index_modify.length
                for (var i = 0; i < count_index_modify; i++) {
                    if (data[i] != null) {
                        $('#gds_ventebundle_' + index_modify[i] + '_taux_remise').val(data[i])
                        doRemiseChange(index_modify[i])
                    }
                }
                RefraichirTaxe()
            }
        })

    }

</script>
<input type="hidden" id="heure"/>